package com.loongxun.playwithyou.ui.activity.user;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loongxun.playwithyou.ApiInterface;
import com.loongxun.playwithyou.App;
import com.loongxun.playwithyou.R;
import com.loongxun.playwithyou.ali.ToAliActivity;
import com.loongxun.playwithyou.bean.Member;
import com.loongxun.playwithyou.bean.Order;
import com.loongxun.playwithyou.bean.SendRequest;
import com.loongxun.playwithyou.network.MyHttpClientRespenseHandler;
import com.loongxun.playwithyou.network.nHttpClient;
import com.loongxun.playwithyou.util.DensityUtils;
import com.loongxun.playwithyou.util.ToastView;
import com.loongxun.playwithyou.view.MyDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单详情
 * Created by Administrator on 2017/8/14.
 */
public class UserOrderInfoActivity extends Activity implements View.OnClickListener{

    private Context context;
    private SendRequest send;
    private String orderNo;
    //start 1、申请取消，2、未审核，3、未通过，4、已通过
    private int orderState,start,onClickWho = 0;
    private Order order = new Order();
    private Member member = new Member();
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private MyDialog mDialog;

    //标题
    private TextView tv_top_title;
    private ImageView iv_nm_img;
    private TextView tv_nm_name,tv_nm_num,
            tv_nm_item_order_no,tv_nm_item_start_time,tv_nm_item_hours_num,
            tv_nm_item_type, tv_nm_item_prive,tv_nm_item_phone,tv_nm_item_state,
            tv_nm_item_examine_no,tv_nm_item_examine_time,tv_nm_item_examine_hours_num,
            tv_nm_item_evaluate,
            tv_nm_item_examine_order_refund,tv_nm_item_examine_reason,
            tv_order_go_to_play,tv_order_go_to_cancel;
    private LinearLayout ll_nm_game;
    private EditText et_nm_item_evaluate;
//    private int cursorPos;    //输入表情前EditText中的文本
    private String inputAfterText;    //是否重置了EditText的内容
    private boolean resetText = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_order_info);
        context = UserOrderInfoActivity.this;

        orderNo = getIntent().getStringExtra("orderNo");
        orderState = getIntent().getIntExtra("orderState", 0);
        start = getIntent().getIntExtra("start",0);
        try {
            send = new SendRequest();
            send.orderNo = orderNo;
            //个人中心订单详情
            if (orderState != 4) {
                nHttpClient.getAll(ApiInterface.USER_ORDER_INFO, send.toOrderMemberInfoJson().toString(), orderHandler);
            }else {
                nHttpClient.getAll(ApiInterface.USER_EXAM_INFO, send.toOrderMemberInfoJson().toString(), orderHandler);
            }
        }catch (Exception e){
            ToastView toast = new ToastView(context, "参数错误");
            toast.show();
        }
        initView();
    }

    private void initView() {
        findViewById(R.id.iv_back).setOnClickListener(this);
        tv_top_title = (TextView) findViewById(R.id.tv_top_title);
        if (orderState != 4) {
            tv_top_title.setText("订单详情");
            findViewById(R.id.ll_user_info).setVisibility(View.VISIBLE);//头像个人资料
            iv_nm_img = (ImageView) findViewById(R.id.iv_nm_img);
            tv_nm_name = (TextView) findViewById(R.id.tv_nm_name);
            findViewById(R.id.ll_nm_address).setVisibility(View.VISIBLE);
            findViewById(R.id.ll_nm_num).setVisibility(View.VISIBLE);
            tv_nm_num = (TextView) findViewById(R.id.tv_nm_num);
            ll_nm_game = (LinearLayout) findViewById(R.id.ll_nm_game);
        }
        //代付款
        if (orderState == 0) {
            findViewById(R.id.ll_nm_item_examine).setVisibility(View.GONE);//审核信息
            findViewById(R.id.ll_nm_item_evaluate).setVisibility(View.GONE);//评价、申请取消
            findViewById(R.id.ll_nm_item_order_btn).setVisibility(View.VISIBLE);//底边按钮
            initViewOrder();
            tv_order_go_to_play = (TextView) findViewById(R.id.tv_order_go_to_play);
            tv_order_go_to_cancel = (TextView) findViewById(R.id.tv_order_go_to_cancel);
            tv_order_go_to_play.setOnClickListener(this);
            tv_order_go_to_cancel.setOnClickListener(this);
        }
        //待确认
        if (orderState == 1) {
            findViewById(R.id.ll_nm_item_examine).setVisibility(View.GONE);//审核信息
            //申请取消
            if (start == 1) {
                findViewById(R.id.ll_nm_item_order).setVisibility(View.GONE);//订单信息
                findViewById(R.id.ll_nm_item_order_btn).setVisibility(View.GONE);//底边按钮
                findViewById(R.id.ll_nm_item_evaluate).setVisibility(View.VISIBLE);//评价、申请取消
                et_nm_item_evaluate = (EditText) findViewById(R.id.et_nm_item_evaluate);
                et_nm_item_evaluate.setHint("请填写您申请取消的原因");
                tv_nm_item_evaluate = (TextView) findViewById(R.id.tv_nm_item_evaluate);
                tv_nm_item_evaluate.setOnClickListener(this);
                tv_nm_item_evaluate.setText("申请取消");
                et_nm_item_evaluate.addTextChangedListener(textWatcher);
                //陪练结束
            }else if (start == 6) {
                findViewById(R.id.ll_nm_item_evaluate).setVisibility(View.GONE);//评价、申请取消
                findViewById(R.id.ll_nm_item_order_btn).setVisibility(View.VISIBLE);//底边按钮
                initViewOrder();
                findViewById(R.id.tv_order_go_to_cancel).setVisibility(View.GONE);
                tv_order_go_to_play = (TextView) findViewById(R.id.tv_order_go_to_play);
                tv_order_go_to_play.setOnClickListener(this);
                tv_order_go_to_play.setText("陪练结束");
                //其他
            }else {
                findViewById(R.id.ll_nm_item_evaluate).setVisibility(View.GONE);//评价、申请取消
                findViewById(R.id.ll_nm_item_order_btn).setVisibility(View.GONE);//底边按钮
                initViewOrder();
            }
        }
        //待评价
        if (orderState == 2) {
            findViewById(R.id.ll_nm_item_order).setVisibility(View.GONE);//订单信息
            findViewById(R.id.ll_nm_item_order_btn).setVisibility(View.GONE);//底边按钮
            findViewById(R.id.ll_nm_item_examine).setVisibility(View.GONE);//审核信息
            findViewById(R.id.ll_nm_item_evaluate).setVisibility(View.VISIBLE);//评价、申请取消
            et_nm_item_evaluate = (EditText) findViewById(R.id.et_nm_item_evaluate);
            et_nm_item_evaluate.setHint("非常感谢您百忙之中的评价");
            tv_nm_item_evaluate = (TextView) findViewById(R.id.tv_nm_item_evaluate);
            tv_nm_item_evaluate.setOnClickListener(this);
            tv_nm_item_evaluate.setText("评价");
            et_nm_item_evaluate.addTextChangedListener(textWatcher);
        }
        //已完成
        if (orderState == 3) {
            findViewById(R.id.ll_nm_item_order_btn).setVisibility(View.GONE);//底边按钮
            findViewById(R.id.ll_nm_item_examine).setVisibility(View.GONE);//审核信息
            findViewById(R.id.ll_nm_item_evaluate).setVisibility(View.GONE);//评价、申请取消
            initViewOrder();
        }
        //取消管理
        if (orderState == 4) {
            findViewById(R.id.ll_user_info).setVisibility(View.GONE);//头像个人资料
            findViewById(R.id.ll_nm_item_order).setVisibility(View.GONE);//订单信息
            findViewById(R.id.ll_nm_item_order_btn).setVisibility(View.GONE);//底边按钮
            findViewById(R.id.ll_nm_item_examine).setVisibility(View.VISIBLE);//审核信息
            findViewById(R.id.ll_nm_item_evaluate).setVisibility(View.GONE);//评价、申请取消
            tv_nm_item_examine_no = (TextView) findViewById(R.id.tv_nm_item_examine_no);
            tv_nm_item_examine_time = (TextView) findViewById(R.id.tv_nm_item_examine_time);
            tv_nm_item_examine_hours_num = (TextView) findViewById(R.id.tv_nm_item_examine_hours_num);
            tv_nm_item_examine_order_refund = (TextView) findViewById(R.id.tv_nm_item_examine_order_refund);
            tv_nm_item_examine_reason = (TextView) findViewById(R.id.tv_nm_item_examine_reason);
            if (start == 2) {
                tv_nm_item_examine_order_refund.setVisibility(View.GONE);
                findViewById(R.id.tv_nm_item_examine_zhong).setVisibility(View.VISIBLE);
                tv_top_title.setText("审核中");
            }else if (start == 3) {
                tv_top_title.setText("已通过");
                //审核信息
                findViewById(R.id.ll_nm_item_examine_yi).setVisibility(View.VISIBLE);
                findViewById(R.id.tv_nm_item_examine_zhong).setVisibility(View.GONE);
                tv_nm_item_examine_order_refund.setVisibility(View.GONE);
            }else if (start == 4) {
                tv_top_title.setText("未通过");
                //审核信息
                findViewById(R.id.ll_nm_item_examine_wei).setVisibility(View.VISIBLE);
                findViewById(R.id.tv_nm_item_examine_zhong).setVisibility(View.GONE);
                tv_nm_item_examine_order_refund.setVisibility(View.VISIBLE);
            }
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            if (!resetText) {
//                cursorPos = getSelectionEnd();                    // 这里用s.toString()而不直接用s是因为如果用s，
                // 那么，inputAfterText和s在内存中指向的是同一个地址，s改变了，
                // inputAfterText也就改变了，那么表情过滤就失败了
//                inputAfterText= s.toString();
//            }
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String str = editable.toString();
            if (str.length()>100) {
                str = str.substring(0,100);
                et_nm_item_evaluate.setText(str);
                et_nm_item_evaluate.setSelection(str.length());
            }
            if (App.containsEmoji(str.toString())) {
                resetText = false;
                // 是表情符号就将文本还原为输入表情符号之前的内容
//                et_nm_item_evaluate.setText(inputAfterText);
//                CharSequence text = et_nm_item_evaluate.getText();
//                if (text instanceof Spannable) {
//                    Spannable spanText = (Spannable) text;
//                    Selection.setSelection(spanText, text.length());
//                }
                new ToastView(context, "禁止使用表情").show();
            }
        }
    };

//    private int getSelectionEnd(){
//        return et_nm_item_evaluate.getText().length();
//    }

    //修改订单状态 orderState（取消订单传值=5，确认订单传值=2）
    private void upOrder(String orderNo,String state) {
        try {
            send = new SendRequest();
            send.orderState = state;
            send.orderNo = orderNo;
            //判断此会员是否为陪玩人员
            nHttpClient.getAll(ApiInterface.USER_UP_ORDER, send.toUpOrderJson().toString(), upOrderHandler);
        }catch (Exception e){
            ToastView toast = new ToastView(context, "参数错误");
            toast.show();
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_order_go_to_play:
                if (orderState == 0) {
                    try {
                        send = new SendRequest();
                        send.orderNo = order.getOrder_no();
                        //待支付订单再次支付的校验
                        nHttpClient.getAll(ApiInterface.IS_TO_PLAY, send.toOrderMemberInfoJson().toString(), isToPlayHandler);
                    }catch (Exception e){
                        ToastView toast = new ToastView(context, "参数错误");
                        toast.show();
                    }
                }else if (orderState == 1) {
                    mDialog = new MyDialog(context,"提示","是否确认陪练结束？");
                    mDialog.show();
                    mDialog.positive.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDialog.dismiss();
                            onClickWho = 2;
                            upOrder(order.getOrder_no(), "2");
                        }
                    });
                    mDialog.negative.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDialog.dismiss();
                        }
                    });
                }
                break;
            case R.id.tv_order_go_to_cancel:
                mDialog = new MyDialog(context,"提示","是否取消订单？");
                mDialog.show();
                mDialog.positive.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDialog.dismiss();
                        onClickWho = 0;
                        upOrder(order.getOrder_no(), "5");
                    }
                });
                mDialog.negative.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDialog.dismiss();
                    }
                });
                break;
            case R.id.tv_nm_item_evaluate:
                if (!resetText) {
                    new ToastView(context, "禁止使用表情").show();
                }else {
                    String string = et_nm_item_evaluate.getText().toString();
                    //评价
                    if (orderState == 2) {
                        if ("".equals(string)) {
                            new ToastView(context, "请输入您的评价").show();
                        } else {
                            try {
                                send = new SendRequest();
                                send.orderNo = order.getOrder_no();
                                send.orderId = order.getOrderId();
                                send.evaluateInfo = string;
                                onClickWho = 3;
                                //保存评价
                                nHttpClient.getAll(ApiInterface.SAVE_EVAL, send.tosaveEvaluateJson().toString(), upOrderHandler);
                            } catch (Exception e) {
                                ToastView toast = new ToastView(context, "参数错误");
                                toast.show();
                            }
                        }
                        //申请取消已支付订单
                    } else if (orderState == 1 && start == 1) {
                        if ("".equals(string)) {
                            new ToastView(context, "请输入您的申请原因").show();
                        } else {
                            try {
                                send = new SendRequest();
                                send.orderId = order.getOrderId();
                                send.orderRefund = string;
                                onClickWho = 4;
                                //保存申请
                                nHttpClient.getAll(ApiInterface.SAVE_EXAM, send.tosaveExamJson().toString(), upOrderHandler);
                            } catch (Exception e) {
                                ToastView toast = new ToastView(context, "参数错误");
                                toast.show();
                            }
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            if (requestCode == 10) {
                if (data.getBooleanExtra("ALi",false)){
                    okOrder();
                }else {
                    failOrder();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //支付成功
    private void okOrder() {
        mDialog = new MyDialog(context,"支付成功","是否继续购物？");
        mDialog.show();
        mDialog.positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                //todo 去购物
            }
        });
        mDialog.negative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                Intent intent = new Intent();
                intent.putExtra("orderState", 1);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });
    }

    //支付失败
    private void failOrder() {
        mDialog = new MyDialog(context,"支付失败","是否继续支付？");
        mDialog.show();
        mDialog.positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mDialog.negative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }

    private void initData() {

        if (orderState != 4) {
            tv_nm_name.setText(member.getMember_name());
            if (!member.getMember_img().equals("")) {
                imageLoader.displayImage(ApiInterface.IMAGES + member.getMember_img(), iv_nm_img, App.options);
            }
            tv_nm_num.setText(member.getClick_num()+"");
            ll_nm_game.removeAllViews();
            ImageView dotIv;
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtils.dp2px(context, 40), DensityUtils.dp2px(context, 40));
            for (int i = 0; i < member.getGameImgs().size(); i++) {
                dotIv = new ImageView(context);
                //设置点的间距
                params.setMargins(DensityUtils.dp2px(context, 5), DensityUtils.dp2px(context, 5), 0,DensityUtils.dp2px(context, 5));
                dotIv.setLayoutParams(params);
                imageLoader.displayImage(ApiInterface.IMAGES + member.getGameImgs().get(i), dotIv, App.options);
                //添加点到view上
                ll_nm_game.addView(dotIv);
            }
        }

        if (orderState == 0) {
            initDataOrder();
        }
        if (orderState == 1) {
            if (start != 1) {
                initDataOrder();
            }
        }
        if (orderState == 3) {
            initDataOrder();
            tv_nm_item_state.setTextColor(this.getResources().getColor(R.color.text_color));//通过获得资源文件进行设置
            tv_nm_item_state.setText("订单已完成");
        }
        if (orderState == 4) {
            tv_nm_item_examine_no.setText("订  单  号："+order.getOrder_no());
            tv_nm_item_examine_time.setText("预约时间："+order.getPlay_start_time());
            tv_nm_item_examine_hours_num.setText("预约时长：共计" +order.getHours_num()+"小时");
            tv_nm_item_examine_reason.setText(order.getExamine_reason());
            tv_nm_item_examine_order_refund.setText("取消原因：" +order.getOrder_refund());
        }
    }

    //订单信息
    private void initDataOrder() {
        tv_nm_item_order_no.setText("订  单  号：" + order.getOrder_no());
        tv_nm_item_start_time.setText("预约时间："+order.getPlay_start_time());
        tv_nm_item_hours_num.setText("预约时长：共计" +order.getHours_num()+"小时");
        if (order.getGame_type() == 0) {
            tv_nm_item_type.setText("游戏类型：王者荣耀");
        }else {
            tv_nm_item_type.setText("游戏类型：英雄联盟");
        }
        tv_nm_item_prive.setText("订单金额："+order.getOrder_all_price()+"元");
        tv_nm_item_phone.setText("下单时间：" + order.getCreate_time());
    }

    //订单控件初始化
    private void initViewOrder() {
        //订单信息
        findViewById(R.id.ll_nm_item_order).setVisibility(View.VISIBLE);
        findViewById(R.id.ll_g_user_address).setVisibility(View.GONE);
        tv_nm_item_order_no = (TextView) findViewById(R.id.tv_nm_item_order_no);
        tv_nm_item_start_time = (TextView) findViewById(R.id.tv_nm_item_start_time);
        tv_nm_item_hours_num = (TextView) findViewById(R.id.tv_nm_item_hours_num);
        tv_nm_item_type = (TextView) findViewById(R.id.tv_nm_item_type);
        tv_nm_item_prive = (TextView) findViewById(R.id.tv_nm_item_prive);
        tv_nm_item_phone = (TextView) findViewById(R.id.tv_nm_item_phone);
        tv_nm_item_state = (TextView) findViewById(R.id.tv_nm_item_state);
    }

    private MyHttpClientRespenseHandler isToPlayHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                Intent intent = new Intent(context,ToAliActivity.class);
                intent.putExtra("orderNo", order.getOrder_no());
                intent.putExtra("subject", "");
                startActivityForResult(intent, 10);
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    private MyHttpClientRespenseHandler upOrderHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
                Intent intent = new Intent();
                intent.putExtra("orderState", onClickWho);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    private MyHttpClientRespenseHandler orderHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            JSONArray itemArray;
            JSONObject orderObject;
            if (succeed == 1) {
                try {
                    List<String> imgs = null;
                    orderObject = json.getJSONObject("data").getJSONObject("playOrder");
                    order.setOrder_no(orderObject.getString("order_no"));
                    order.setOrderId(orderObject.getString("order_id"));
                    order.setPlay_start_time(orderObject.getString("play_start_time"));
                    order.setHours_num(orderObject.getInt("hours_num"));
                    order.setOrder_all_price(orderObject.getDouble("order_all_price"));
                    order.setOrder_state(orderObject.getInt("order_state"));
                    order.setCreate_time(orderObject.getString("createDime"));

                    if (orderState == 4) {
                        orderObject = json.getJSONObject("data").getJSONObject("playExamine1");
                        order.setExamine_reason(orderObject.getString("examine_reason"));
                        order.setOrder_refund(orderObject.getString("order_refund"));
                    } else {
                        String user = json.getJSONObject("data").getString("playMember");
                        if (!user.equals("null")) {
                            JSONObject userObject = json.getJSONObject("data").getJSONObject("playMember");
                            member.setMember_name(userObject.getString("member_name"));
                            member.setMember_img(userObject.getString("member_img"));
                            member.setClick_num(userObject.getInt("click_num"));
                            imgs = new ArrayList<>();
                            if (!"null".equals(userObject.getString("memberGames"))) {
                                itemArray = userObject.getJSONArray("memberGames");
                                for(int i = 0;i < itemArray.length();i++) {
                                    JSONObject jsonObject = itemArray.getJSONObject(i);
                                    imgs.add(jsonObject.optString("game_logo"));
                                }
                            }
                            member.setGameImgs(imgs);
                        }else {
                            member.setMember_name("暂无昵称");
                            member.setMember_img("");
                            member.setClick_num(0);
                            member.setGameImgs(new ArrayList<String>());
                        }
                    }
                    initData();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };
}
